package config

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"strconv"
	"strings"
)

var g_globalConf = make(map[string]string, 4)

// func (cfg *PoolConfig) GetNextPortal() string {
// 	var idx uint32
// 	var count = uint32(len(cfg.PortalList))
// 	idx = atomic.AddUint32(&cfg.portalIndex, 1)
// 	return cfg.PortalList[idx%count]
// }

// func inArray(strArray []string, key string) bool {
// 	var item string
// 	for _, item = range strArray {
// 		if item == key {
// 			return true
// 		}
// 	}
// 	return false
// }

func LoadConfig(configFile string) error {

	confFp, err := os.Open(configFile)
	if err != nil {
		return err
	}
	defer func() { confFp.Close() }()

	buff := bufio.NewReader(confFp)

	var key string
	var val string
	var lineno int = 0
	var idx int

	for {
		line, err := buff.ReadString('\n')
		lineno++

		if err != nil || io.EOF == err {
			break
		}

		line = strings.TrimSpace(line)
		if strings.HasPrefix(line, "#") {
			continue
		}

		if len(line) < 3 {
			continue
		}

		idx = strings.Index(line, "=")
		if len(line) <= 1 {
			continue
		}
		if idx < 0 {
			return fmt.Errorf("invalid line(no '='): %s ", line)
		}

		key = line[0:idx]
		key = strings.TrimSpace(key)

		val = line[idx+1:]

		// 把一行后的 以#的注释去掉
		sharpPos := strings.Index(val, "#")
		if sharpPos >= 0 {
			val = val[:sharpPos]
		}
		val = strings.TrimSpace(val)

		if strings.HasPrefix(key, "pool.") { /*跳过以pool.开头的配置项*/
			continue
		}
		g_globalConf[key] = val
	}

	return nil
}

func Get(key string) string {
	return g_globalConf[key]
}

func GetInt(key string) int {
	val := g_globalConf[key]
	b, err := strconv.Atoi(val)
	if err != nil {
		return 0
	}
	return b
}
